package org.msfj.toilets.socket.tcp;

import org.msfj.toilets.config.ToiletConfig;
import org.msfj.toilets.socket.DataHandler;
import org.tio.core.ChannelContext;
import org.tio.core.GroupContext;
import org.tio.core.Node;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioHandler;

import java.nio.ByteBuffer;

/**
 * @Description:
 * @User: Administrator
 * @Date: 2018/10/4 0004
 */
public class TioTcpHandler implements ServerAioHandler {

    private ToiletConfig toiletConfig;

    public TioTcpHandler (ToiletConfig toiletConfig){
        this.toiletConfig = toiletConfig;
    }

    @Override
    public Packet decode(ByteBuffer byteBuffer, int i, int i1, int i2, ChannelContext channelContext) {
        TcpPacket tcpPacket = new TcpPacket();
        byte[] dst = new byte[i];
        byteBuffer.get(dst);
        tcpPacket.setData(dst);
        return tcpPacket;
    }

    @Override
    public ByteBuffer encode(Packet packet, GroupContext groupContext, ChannelContext channelContext) {
        return null;
    }

    /**
     * 处理消息
     */
    @Override
    public void handler(Packet packet, ChannelContext channelContext) {
        TcpPacket tcpPacket = (TcpPacket) packet;
        byte[] bytes = tcpPacket.getData();
        int size = tcpPacket.getByteCount();
        Node clientNode = channelContext.getClientNode();
        DataHandler.handler(bytes, size, clientNode,"TCP",toiletConfig);
    }
}
